package be.vdabantwerpen.gow.servlets;

import be.vdabantwerpen.gow.entities.GOWUser;
import be.vdabantwerpen.gow.entities.Post;
import be.vdabantwerpen.gow.exceptions.PostNotFoundException;
import be.vdabantwerpen.gow.exceptions.UserNotFoundException;
import be.vdabantwerpen.gow.services.PostService;
import be.vdabantwerpen.gow.services.PostServiceImpl;
import be.vdabantwerpen.gow.services.UserService;
import be.vdabantwerpen.gow.services.UserServiceImpl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ViewProfileServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private static final String VIEW = "/WEB-INF/jsp/user/profile.jsp";
    private static final UserService userService = new UserServiceImpl();
    private static final PostService postService = new PostServiceImpl();

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<String> errors = new ArrayList<String>();
        String userIdAsString = request.getParameter("userId");
        if (userIdAsString != null) {
            try {
                GOWUser user = userService.read(Integer.parseInt(userIdAsString));
                request.setAttribute("ViewedUser", user);
                List<Post> posts = postService.findByUser(user);
                request.setAttribute("posts", posts);
            } catch (NumberFormatException ex) {
                errors.add("UserId moet een getal zijn");
            } catch (UserNotFoundException ex) {
                errors.add("User bestaat niet");
            } catch (PostNotFoundException ex) {
            	// User heeft geen posts
            }
        } else {
            errors.add("Geen UserID meegegeven.");
        }
        if (!errors.isEmpty()) {
            request.setAttribute("errors", errors);
        }
        request.getRequestDispatcher(VIEW).forward(request, response);

    }
}